package cn.edu.ctbu.firstdp.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;


@Aspect
@Component
@Slf4j
public class HttpAspect {
    @Pointcut("execution(* cn.edu.ctbu.firstdp.api.StudentApiController.*(..))")
    public void log(){
    }
    @Before("log()")
    public void doBefore(){
        //log.info("do before");
        log.info("准备开始执行api...");
    }
    @After("log()")
    public void doAfter(){
        log.info("执行api完，准备返回...");
        //System.out.println("222");
    }
    @AfterReturning(returning = "object",pointcut = "log()")
    public void doAfterReturning(Object object){
        log.info("response={}",object);
    }
    @Around("log()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable{
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Object obj= pjp.proceed(pjp.getArgs());//真正执行方法的地方
        stopWatch.stop();
        long cost = stopWatch.getTotalTimeMillis();//获取执行的时间
        MethodSignature signature = (MethodSignature)pjp.getSignature();
        String methodName=signature.getDeclaringTypeName()+"."+signature.getName();
        log.info("----------执行"+methodName+"方法,用时:"+cost+"ms---------- ");
        return obj;
    }
}

